package com.hc.common.service.impl;

import com.hc.common.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Resource
    private JavaMailSender sender;

    @Override
    public void sendTextEmail(String from, String to, String cc, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        //发件人
        message.setFrom(from);
        //收件人
        message.setTo(to);
        //抄送人
        message.setCc(cc);
        //邮件主题
        message.setSubject(subject);
        //邮件内容
        message.setText(content);
        //发送邮件
        sender.send(message);
    }

    @Override
    public void sendMimeEmail(String from, String to, String subject, String content) {
        MimeMessage message = sender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            message.setSubject(subject);
            helper.setText(content, true);
            sender.send(message);
            log.info("邮件已经发送！");
        } catch (MessagingException e) {
            log.error("发送邮件时发生异常：" + e);
        }
    }

    @Override
    public void sendsAttachmentEmail(String from, String to, String subject, String content, String file) {
        MimeMessage message = sender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            //携带附件
            FileSystemResource fsr = new FileSystemResource(file);
            String fileName = file.substring(file.lastIndexOf("/"));
            helper.addAttachment(fileName, fsr);

            sender.send(message);
            log.info("邮件加附件发送成功！");
        } catch (MessagingException e) {
            log.error("发送失败：" + e);
        }
    }

}
